import { _decorator, Component, Node, Vec2, Vec3, UITransform, EventTouch, Input, input, Touch, math } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('Joystick')
export class Joystick extends Component {
    @property(Node)
    stick: Node = null;

    @property
    radius: number = 80;

    private _direction: Vec2 = new Vec2(0, 0);
    
    public getDirection(): Vec2 {
        return this._direction.clone();
    }

    onLoad() {
        this.node.on(Input.EventType.TOUCH_START, this._onTouch, this);
        this.node.on(Input.EventType.TOUCH_MOVE, this._onTouch, this);
        this.node.on(Input.EventType.TOUCH_END, this._onTouchEnd, this);
        this.node.on(Input.EventType.TOUCH_CANCEL, this._onTouchEnd, this);
    }

    _onTouch(event: EventTouch) {
        const uiPos = event.getUILocation();
        const localPos = this.node.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(uiPos.x, uiPos.y));
        let dir = new Vec2(localPos.x, localPos.y);
        const len = dir.length();

        if (len > this.radius) {
            dir.normalize().multiplyScalar(this.radius);
        }

        this.stick.setPosition(new Vec3(dir.x, dir.y, 0));
        this._direction = dir.clone().normalize();
    }

    _onTouchEnd() {
        this.stick.setPosition(Vec3.ZERO);
        this._direction.set(0, 0);
    }
}
